# This file is a part of Conspire
# $Id: forms.py 65 2007-04-23 22:05:15Z b.ghose $

from django import newforms as forms
from django.contrib.auth.models import User
from freedel.conspire.models import LEVELS
from django.core import validators

attrs_dict = { 'class': 'required' }

class RegistrationForm(forms.Form):

    first_name = forms.CharField(
        max_length = 30,
        widget = forms.TextInput(attrs = attrs_dict),
        label = 'First Name:'
        )

    last_name = forms.CharField(
        max_length = 30,
        widget = forms.TextInput(attrs = attrs_dict),
        label = 'Last Name:'
        )

    username = forms.CharField(
        max_length = 30,
        widget = forms .TextInput(attrs = attrs_dict),
        label = 'Username:'
        )

    email = forms.EmailField(
        widget = forms.TextInput(attrs = dict(attrs_dict)),
        label = 'Email Address:'
        )

    password1 = forms.CharField(
        widget = forms.PasswordInput(attrs = attrs_dict),
        label = 'Password:'
        )

    password2 = forms.CharField(
        widget = forms.PasswordInput(attrs = attrs_dict),
        label = 'Confirm Password:'
        )

    affiliation = forms.CharField(
        max_length = 100,
        widget = forms.TextInput(),
        label = 'Organisation:',
        required = False
        )

    location = forms.CharField(
        max_length = 50,
        widget = forms.TextInput(attrs = attrs_dict),
        label = 'Location:',
        required = False
        )
    
    accomodation = forms.BooleanField(
        widget = forms.CheckboxInput(),
        label = 'Do you require accomodation?',
        required = False
        )

    travel_assistance = forms.BooleanField(
        widget = forms.CheckboxInput(attrs = {'onclick' : 'handler()'}),
        label = 'Do you require travel assistance?',
        required = False
        )
    
    travel_info = forms.CharField(
        widget = forms.Textarea(attrs = {'cols' : 40,
                                         'rows' : 3}),
        label = 'Your detailed travel plan:',
        required = False
        )
    
    personal_url = forms.URLField(
        widget = forms.TextInput(),
        label = 'Your website / blog (if any):',
        required = False
        )
    
    tracks = forms.MultipleChoiceField(
        widget = forms.SelectMultiple(),
        label = 'Tracks of Interest:',
        choices = []
        )
    
    comments = forms.CharField(
        max_length = 120,
        widget = forms.Textarea(attrs = {'cols' : 40,
                                         'rows' : 10}),
        label = 'Additional comments:',
        required = False
        )
    
    photograph = forms.Field(
        label = 'Your photograph:',
        widget = forms.FileInput(),
        required = False
        )

    bio = forms.CharField(
        label = 'Short Bio:',
        widget = forms.Textarea(attrs = {'cols' : 40,
                                         'rows' : 10}),
        required = False
        )
    
    def clean_username(self):
        """ Raise error if username is not valid.

        """
        
        if self.clean_data.get('username', None):

            try:
                user = User.objects.get(username__exact = \
                                        self.clean_data['username'])
            except User.DoesNotExist:
                return self.clean_data['username']
            
            raise forms.ValidationError('Username already taken.' 
                                        ' Please choose another one.')


        return

    def clean_email(self):
        """ Raise error if email is not valid.
        
        """

        try:
            user = User.objects.get(email__exact = \
                                    self.clean_data['email'])
        except User.DoesNotExist:
            return self.clean_data['email']

        raise forms.ValidationError('Email already registered.' 
                                    ' Please choose another one.')

        
    def clean_password2(self):
        """ Raise error if password is not valid.

        """

        if self.clean_data['password2'] != self.clean_data['password1']:
            raise forms.ValidationError('Passwords do not match.')

        return self.clean_data['password2']

    def clean_photograph(self):
        """ Raise error if image is not valid.
        
        """

        from PIL import Image
        from cStringIO import StringIO

        try:
            content = self.clean_data['photograph']['content']
        except TypeError:
            return None
        
        if not content:
            raise forms.ValidationError('No file was submitted.')
        
        try:
            Image.open(StringIO(content))
        except IOError:
            raise forms.ValidationError('Upload a valid image. '
                                        'The file you uploaded was either '
                                        'not an image or a corrupted image.')

        return self.clean_data['photograph']


class TalkSubmissionForm(forms.Form):
    name = forms.CharField(max_length=255,
                           widget=forms.TextInput(attrs = attrs_dict),
                           label=u'Talk title:')
    abstract = forms.CharField(max_length=1000,
                               widget=forms.Textarea(attrs = attrs_dict),
                               label=u'Talk abstract:')
    presentation_file = forms.Field(label=u'Talk slides (in OpenDocument, PDF or plain text):',
                                    widget=forms.FileInput())
    category = forms.ChoiceField(widget=forms.Select(),
                                 label=u'Talk category:')
    equipment = forms.BooleanField(widget=forms.CheckboxInput(),
                                   label=u'Do you need any special equipment?')
    
    level = forms.ChoiceField(widget=forms.Select(),
                              label=u'Target audience:',
                              choices = LEVELS
                              )
    comments = forms.CharField(widget=forms.Textarea(),
                               label=u'Additional comments:')
    
    def clean_talk_name(self):
        if self.clean_data.get('name', None):
            try:
                name = Talk.objects.get(username__exact=self.clean_data['name'])
            except:
                return self.clean_data['name']
            raise forms.ValidationError(u'''A talk by the name "%s" has
                                        already been registered. Please choose another one.''' %
                                        self.clean_data['name']) 


class FeedbackForm(forms.Form):
    username = forms.CharField(
        max_length = 30,
        widget = forms.TextInput(attrs = attrs_dict),
        label = u'Your name:'
        )

    email = forms.EmailField(
        widget = forms.TextInput(attrs = dict(attrs_dict)),
        label = u'Email Address:'
        )

    talks = forms.ChoiceField(
        widget = forms.Select(),
        label = u'Related talk:',
        required = False,
        choices = []
        )

    feedback = forms.CharField(
        label = 'Your feedback:',
        widget = forms.Textarea(attrs = {'cols' : 40,
                                         'rows' : 10,
                                         'class' : 'required'}),
        required = True
        )
